package com.xudu.filter;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xudu.common.Result;
import com.xudu.entity.Log;
import com.xudu.mapper.LogMapper;
import com.xudu.service.ILogService;
import com.xudu.utils.IpUtil;
import com.xudu.utils.JWTUtil;
import com.xudu.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;

import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;


/**
 * ClassName: MyFilter
 * Description:
 *
 * @Author xudu
 * @Create 2024/4/26
 */
@Slf4j
@WebFilter("/*")
public class MyFilter implements Filter {

    @Autowired
    private ILogService iLogService;

    @Autowired
    private RedisUtils redisUtils;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("过滤器初始化！");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("正在执行过滤器！");
        //强转servletRequest为HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取IP地址
        String ip = IpUtil.getIpAddr(request);
        log.info(ip);
        String method = request.getMethod();
        log.info(method);
        String url = request.getRequestURL().toString();
        log.info(url);
        String time = DateUtil.now();
        log.info(time);

        //组装实体类
        Log log1 = new Log();
        log1.setIp(ip);
        log1.setMethod(method);
        log1.setTime(time);
        log1.setUrl(url);
//        Log build = Log.builder()
//                .ip(ip)
//                .method(method)
//                .url(url)
//                .time(time)
//                .build();
        iLogService.save(log1);

        //测试用
        if (url.contains("gread") ) {
            log.info("计算成绩请求测试放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //判断是否是登录或注册请求
        if (url.contains("login") || url.contains("register")) {
            log.info("登录或注册请求直接放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        String token = request.getHeader("token");
        String username = JWTUtil.getUsername(token);
        if (token == null) {
            Result error = Result.error("请先注册或登陆账号");
            response.setContentType("application/json;charset=UTF-8");
            String str = JSONObject.toJSONString(error);
            response.getWriter().println(str);
            return;
        }


        //验证token
        Boolean redisExist = redisUtils.isRedisExist(username);
        //判断redis里是否存在该用户信息
        if (redisExist) {
            //如果存在判断token是否正确
            String redisContent = redisUtils.getRedisContent(username);
            if (token.equals(redisContent)) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                Result rp = Result.error("验证token失败！");
                response.setContentType("application/json;charset=UTF-8");
                String str = JSONObject.toJSONString(rp);
                response.getWriter().println(str);
            }
        }else {
            Result rp = Result.error("token已过期，请重新登陆");
            response.setContentType("application/json;charset=UTF-8");
            String str = JSONObject.toJSONString(rp);
            response.getWriter().println(str);
        }

//        try {
//
//            JWTUtil.verify(token);
//        } catch (Exception e) {
//            Result rp = Result.error("验证token失败！");
//            response.setContentType("application/json;charset=UTF-8");
//            String str = JSONObject.toJSONString(rp);
//            response.getWriter().println(str);
//            return;
//        }
//        //验证token成功，直接放行
//        filterChain.doFilter(servletRequest,servletResponse);

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        log.info("过滤器已销毁！");
    }
}

